//
//  LoadingUtil.swift
//  GreenDeal
//
//  Created by Moennig Q on 2023/3/7.
//

import UIKit

class ModelViewUtil: NSObject {
    var alertView: UIView!
    var modelView: UIView!
    var container: LoadingView!
    static let shared = ModelViewUtil()
    
    //当前界面是否是横屏
    func showLoadingView(_ showText: String = R.string.localizable.loading(),parentView: UIView? = nil){
        if self.container == nil{
            var superView: UIView?
            if parentView != nil{
                superView = parentView!
            }else {
                if let rootVCView = Tool.getRootView(){
                    superView = rootVCView
                }
            }
            if superView != nil{
                container = LoadingView()
                container.loadingLabel.text = showText
                superView!.addSubview(container)
                container.snp.makeConstraints { make in
                    make.edges.equalToSuperview()
                }
                superView!.bringSubviewToFront(container)
            }
        }
    }
    func hideLoadingView(){
        if let _ = self.container{
            self.container.actitveView.stopAnimating()
            self.container.removeFromSuperview()
            self.container = nil
        }
    }
    func hideUpdatingView(){
        if let _ = self.container{
            container.loadingLabel.text = R.string.localizable.updated()
            container.actitveView.stopAnimating()
            container.actitveView.isHidden = true
            container.imageView.isHidden = false
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1.0) {[weak self] in
                guard let strongSelf = self else {return }
                strongSelf.container.removeFromSuperview()
                strongSelf.container = nil
            }
        }
    }
    //MARK: - 只用于提示框,parentView用于present view controller(因为alert不加在presened vc上，直接加在Tool.getRootView()，alertview会显示在present vc的后边)
    func showAlertView(_ view: UIView,parentView: UIView? = nil){
        var rootVCView: UIView!
        if let view = parentView {
            rootVCView = view
        }else if let view = Tool.getRootView(){
            rootVCView = view
        }else{
            return
        }
        //如果已经存擦就先删除
        if let alertView = self.alertView, let _ = alertView.superview {
            self.alertView.removeFromSuperview()
        }
        self.alertView = view
        rootVCView.addSubview(self.alertView)
        self.alertView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
    }
}
